<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <!-- 修改：药品ID改为下拉框 -->
      <el-form-item label="药品ID" prop="drugId">
        <el-select
          v-model="queryParams.drugId"
          placeholder="请选择药品"
          clearable
          filterable
        >
          <el-option
            v-for="drug in drugList"
            :key="drug.drugId"
            :label="`${drug.drugId}（${drug.drugName}）`"
            :value="drug.drugId"
          />
        </el-select>
      </el-form-item>

      <!-- 修改：类型名称改为下拉框 -->
      <el-form-item label="类型名称" prop="typeName">
        <el-select
          v-model="queryParams.typeName"
          placeholder="请选择类型"
          clearable
        >
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="是否售卖" prop="isSale">
        <el-select v-model="queryParams.isSale" placeholder="请选择是否售卖" clearable>
          <!-- 修改：使用数字值而不是字符串 -->
          <el-option key="1" label="是" :value="1" />
          <el-option key="0" label="否" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['BasicSettings:management:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['BasicSettings:management:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['BasicSettings:management:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['BasicSettings:management:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="managementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="managementId" />

      <!-- 修改药品ID列的显示 -->
      <el-table-column label="药品ID" align="center" prop="drugId">
        <template slot-scope="scope">
          {{ scope.row.drugId }}（{{ getDrugName(scope.row.drugId) }}）
        </template>
      </el-table-column>

      <el-table-column label="类型名称" align="center" prop="typeName" />
      <el-table-column label="是否售卖" align="center" prop="isSale">
        <template slot-scope="scope">
          <!-- 修改：使用数字比较而不是字符串比较 -->
          {{ scope.row.isSale === 1 ? '是' : '否' }}
        </template>
      </el-table-column>
        <!-- 操作列不变 -->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['BasicSettings:management:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['BasicSettings:management:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改药品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <!-- 药品ID下拉框 -->
        <!-- 修改为（输入框） -->
        <el-form-item label="药品ID" prop="drugId">
          <el-input
            v-model="form.drugId"
            placeholder="请输入药品ID"
            clearable
          />
        </el-form-item>

        <!-- 类型名称下拉框 -->
        <el-form-item label="类型名称" prop="typeName">
          <el-select
            v-model="form.typeName"
          placeholder="请选择类型"
          clearable
          >
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
          </el-select>
        </el-form-item>

        <el-form-item label="是否售卖" prop="isSale">
          <el-select v-model="form.isSale" placeholder="请选择是否售卖">
            <!-- 修改：使用数字值而不是字符串 -->
            <el-option key="1" label="是" :value="1" />
            <el-option key="0" label="否" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listManagement, getManagement, delManagement, addManagement, updateManagement } from "@/api/BasicSettings/management"
import { listDrug } from "@/api/pharmacy/drug" // 新增引入
import { listPharmacyStock } from "@/api/pharmacy/pharmacyStock" // 新增引入
import drugAndPharmacy from "@/api/pharmacy/mixins/drugAndPharmacy";

export default {
  name: "Management",
  dicts: ['yes_or_no'],
  mixins: [drugAndPharmacy],
  data() {
    return {
      drugMap: new Map(), // 新增：药品映射表
      drugList: [], // 新增：药品列表数据
      typeOptions: [ // 新增：类型名称选项
        { label: '中药', value: '中药' },
        { label: '西药', value: '西药' }
      ],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 药品管理表格数据
      managementList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        drugId: null,
        typeName: null,
        isSale: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        drugId: [
          { required: true, message: "药品ID不能为空", trigger: "blur" }
        ],
      }
    }
  },
  async created() {
    // 先加载药品数据
    await this.loadDrugData()
    // 然后加载管理数据
    this.getList()
  },
  methods: {
    /** 新增：处理是否售卖状态变更 */
    async handleSaleChange(value) {
      // 只有从"是"改为"否"时才需要检查
      if (value === 0 && this.form.managementId) {
        try {
          const loading = this.$loading({
            lock: true,
            text: '正在检查药品库存...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })

          const response = await listPharmacyStock({
            drugId: this.form.drugId,
            pageNum: 1,
            pageSize: 1000
          })

          loading.close()

          const hasStock = response.rows.some(item => item.quantity > 0)

          if (hasStock) {
            this.$modal.msgError("该药品仍有库存余量，不能设置为不售卖")
            // 恢复为"是"
            this.$nextTick(() => {
              this.form.isSale = 1
            })
          }
        } catch (error) {
          console.error('查询库存失败:', error)
          this.$modal.msgError("查询库存失败，请稍后再试")
          this.$nextTick(() => {
            this.form.isSale = 1
          })
        }
      }
    },

    /** 修改：异步加载药品数据 */
    async loadDrugData() {
      try {
        const response = await listDrug({ pageNum: 1, pageSize: 1000 })
        this.drugList = response.rows // 保存药品列表数据
        response.rows.forEach(drug => {
          this.drugMap.set(drug.drugId, drug.drugName)
        })
      } catch (error) {
        console.error('加载药品数据失败:', error)
      }
    },

    /** 根据药品ID获取药品名 */
    getDrugName(drugId) {
      return this.drugMap.get(drugId) || '未知药品'
    },

    /** 查询药品管理列表 */
    getList() {
      this.loading = true
      listManagement(this.queryParams).then(response => {
        this.managementList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        managementId: null,
        drugId: null,
        typeName: null,
        isSale: null,
        remark: null,
        createTime: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.managementId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加药品管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const managementId = row.managementId || this.ids
      getManagement(managementId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改药品管理"
      })
    },
    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          // 检查是否要将售卖状态改为"否"
          if (this.form.isSale === 0 && this.form.managementId) {
            try {
              // 显示加载中
              const loading = this.$loading({
                lock: true,
                text: '正在检查药品库存...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
              })

              // 查询该药品的库存
              const response = await listPharmacyStock({
                drugId: this.form.drugId,
                pageNum: 1,
                pageSize: 1000 // 查询足够多的数据
              })

              loading.close()

              // 检查是否有库存余量
              const hasStock = response.rows.some(item => item.quantity > 0)

              if (hasStock) {
                this.$modal.msgError("该药品仍有库存余量，不能设置为不售卖")
                return
              }
            } catch (error) {
              console.error('查询库存失败:', error)
              this.$modal.msgError("查询库存失败，请稍后再试")
              return
            }
          }

          // 执行原保存逻辑
          if (this.form.managementId != null) {
            updateManagement(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            }).catch(error => {
              this.$modal.msgError(error.message || "修改失败")
            })
          } else {
            addManagement(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            }).catch(error => {
              this.$modal.msgError(error.message || "新增失败")
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const managementIds = row.managementId || this.ids
      this.$modal.confirm('是否确认删除药品管理编号为"' + managementIds + '"的数据项？').then(function() {
        return delManagement(managementIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('BasicSettings/management/export', {
        ...this.queryParams
      }, `management_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
